package ai.people.core.web.util;

import ai.people.netmon.utils.UUIDUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;

/**
 * @author yuanqinglong
 * @date 2022/8/5 18:18
 */
public class FileUtil {


    /**
     * 将本地文件转成MultipartFile
     *
     * @param byteArrayOutputStream 字节数组输出流
     * @return {@link MultipartFile}
     */
    public static MultipartFile toMultipartFile(ByteArrayOutputStream byteArrayOutputStream) {
        //先将本地文件转化成FileItem
        FileItem fileItem = createFileItem(byteArrayOutputStream);
        return new CommonsMultipartFile(fileItem);
    }

    /**
     * 根据filePath将puppeteer截取到的图片转成FileItem
     *
     * @param filePath 文件路径
     * @return {@link FileItem}
     */
    public static FileItem createFileItem(String filePath) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        String fieldName = UUIDUtils.getShort()+".xlsx"; //文件名
        FileItem item = factory.createItem(fieldName, "application/zip", true, fieldName);
        File newFile = new File(filePath);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(newFile);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }


    /**
     * 创建文件项
     * 根据filePath将puppeteer截取到的图片转成FileItem
     *
     * @param outputStream 输出流
     * @return {@link FileItem}
     */
    public static FileItem createFileItem(ByteArrayOutputStream outputStream) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        String fieldName = UUIDUtils.getShort()+".xlsx"; //文件名
        FileItem item = factory.createItem(fieldName, "application/zip", true, fieldName);
        try {
            OutputStream os = item.getOutputStream();
            os.write(outputStream.toByteArray());
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }
}
